/**
 * UninaDocentiSync - A Java application to synchronize Unina resources
 * Copyright (C) 2011  Fabio Scippacercola (nonplay.programmer@gmail.com)
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

/*
 * UninaSelecter.java
 *
 * Created on Apr 20, 2011, 10:52:08 PM
 */

package uninadocentisync.guibeans;

import java.awt.Frame;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
import uninadocenti.framework.Docente;
import uninadocenti.framework.Insegnamento;
import uninadocenti.framework.WebDocentiUnina;

/**
 *
 * @author Fabio Scippacercola (nonplay.programmer@gmail.com)
 */
public class UninaSelecter extends javax.swing.JDialog {

    /** Creates new form UninaSelecter */
    protected UninaSelecter(java.awt.Frame parent, boolean modal, WebDocentiUnina w, Selection mode)
    {
        super(parent, modal);
        this.webUnina = w;
        this.mode = mode;
        initComponents();
        changeMode();
    }

    private static enum Selection
    {
        DOCENTE, INSEGNAMENTO, DocANDInsSTEP1, DocAndInsSTEP2
    };

    private void changeMode()
    {
        if (mode == Selection.DOCENTE || mode == Selection.DocANDInsSTEP1)
        {
            this.docentePanel.setVisible(true);
            this.insegnamentoPanel.setVisible(false);
            this.backButton.setText("Annulla");
        }
        else
        {
            this.docentePanel.setVisible(false);
            this.insegnamentoPanel.setVisible(true);
            this.backButton.setText("Indietro");
        }
    }



    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        docentePanel = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        docenteField = new javax.swing.JTextField();
        searchButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        docentiList = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        insegnamentoPanel = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        insegnamentoList = new javax.swing.JList();
        jLabel3 = new javax.swing.JLabel();
        backButton = new javax.swing.JButton();
        frwdButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Seleziona risorsa WebDocenti...");

        jLabel2.setText("Seleziona Docente:");

        docenteField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                docenteFieldActionPerformed(evt);
            }
        });

        searchButton.setText("Cerca...");
        searchButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchButtonActionPerformed(evt);
            }
        });

        docentiList.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Cognome", "Nome", "Dipartimento"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        docentiList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        docentiList.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                docentiListMouseClicked(evt);
            }
        });
        docentiList.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                docentiListKeyReleased(evt);
            }
        });
        jScrollPane1.setViewportView(docentiList);
        docentiList.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);

        javax.swing.GroupLayout docentePanelLayout = new javax.swing.GroupLayout(docentePanel);
        docentePanel.setLayout(docentePanelLayout);
        docentePanelLayout.setHorizontalGroup(
            docentePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(docentePanelLayout.createSequentialGroup()
                .addGroup(docentePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addGroup(docentePanelLayout.createSequentialGroup()
                        .addComponent(docenteField, javax.swing.GroupLayout.DEFAULT_SIZE, 505, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(searchButton, javax.swing.GroupLayout.DEFAULT_SIZE, 80, Short.MAX_VALUE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 591, Short.MAX_VALUE))
                .addContainerGap())
        );
        docentePanelLayout.setVerticalGroup(
            docentePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(docentePanelLayout.createSequentialGroup()
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(docentePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(docenteField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(searchButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 55, Short.MAX_VALUE))
        );

        jLabel1.setText("Seleziona");

        insegnamentoList.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                insegnamentoListMouseClicked(evt);
            }
        });
        insegnamentoList.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                insegnamentoListKeyReleased(evt);
            }
        });
        jScrollPane2.setViewportView(insegnamentoList);

        jLabel3.setText("Seleziona Insegnamento:");

        javax.swing.GroupLayout insegnamentoPanelLayout = new javax.swing.GroupLayout(insegnamentoPanel);
        insegnamentoPanel.setLayout(insegnamentoPanelLayout);
        insegnamentoPanelLayout.setHorizontalGroup(
            insegnamentoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 603, Short.MAX_VALUE)
            .addGroup(insegnamentoPanelLayout.createSequentialGroup()
                .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 591, Short.MAX_VALUE)
                .addContainerGap())
        );
        insegnamentoPanelLayout.setVerticalGroup(
            insegnamentoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(insegnamentoPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 110, Short.MAX_VALUE))
        );

        backButton.setText("Indietro");
        backButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                backButtonActionPerformed(evt);
            }
        });

        frwdButton.setText("Avanti");
        frwdButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                frwdButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(insegnamentoPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(docentePanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel1)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(backButton, javax.swing.GroupLayout.DEFAULT_SIZE, 292, Short.MAX_VALUE)
                        .addGap(18, 18, 18)
                        .addComponent(frwdButton, javax.swing.GroupLayout.DEFAULT_SIZE, 293, Short.MAX_VALUE))
                    .addComponent(jProgressBar1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 603, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(docentePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(insegnamentoPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(41, 41, 41)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(backButton)
                    .addComponent(frwdButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 12, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void backButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backButtonActionPerformed
        if (mode != Selection.DocAndInsSTEP2)
        {
            dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
        }
        else
        {
            mode = Selection.DocANDInsSTEP1;
            changeMode();
        }
        if (worker != null)
        {
            worker.interrupt();
            jProgressBar1.setIndeterminate(false);
        }
    }//GEN-LAST:event_backButtonActionPerformed

    private void frwdButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_frwdButtonActionPerformed
        if (mode == Selection.DOCENTE)
        {
            if (docentiList.getSelectedRow() >= 0)
            {
                docSelected = listDocenti.get(docentiList.getSelectedRow());
                setVisible(false);
            }
        }
        else if (mode == Selection.INSEGNAMENTO || mode == Selection.DocAndInsSTEP2)
        {
            if (insegnamentoList.getSelectedIndex() >= 0)
            {
                insSelected = listInsegnamenti.get(insegnamentoList.getSelectedIndex());
                setVisible(false);
            }
        }
        else if (docentiList.getSelectedRow() >= 0)
        {
            docSelected = listDocenti.get(docentiList.getSelectedRow());
            updateInsList();
            mode = Selection.DocAndInsSTEP2;
            changeMode();
        }
    }//GEN-LAST:event_frwdButtonActionPerformed

    private void updateInsList()
    {
        if (worker != null)
            worker.interrupt();

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                insegnamentoList.setModel(new DefaultListModel());
            }
        });

        worker = new Thread() {
            @Override
            public void run() {
                super.run();
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        jProgressBar1.setIndeterminate(true);
                    }
                });
                final DefaultListModel m = new DefaultListModel();
                try
                {
                    listInsegnamenti = webUnina.lookupInsegnamenti(docSelected);
                    for (Insegnamento ins : listInsegnamenti)
                        m.addElement(ins.getNomeInsegnamento());

                    if (listInsegnamenti.isEmpty()) {
                        JOptionPane.showMessageDialog(UninaSelecter.this,
                                "Nessun insegnamento trovato!\nProva a cambiare i dati di login.\nSe il problema persiste contattare lo sviluppatore.",
                                "Attenzione!", JOptionPane.WARNING_MESSAGE);
                    }
                }
                catch (IOException e)
                {
                    exceptionThrown(e);
                }
                finally
                {
                    if (!isInterrupted())
                    {
                        SwingUtilities.invokeLater(new Runnable() {
                            public void run() {
                                insegnamentoList.setModel(m);
                                jProgressBar1.setIndeterminate(false);
                            }
                        });
                    }
                }
            }
        };
        worker.start();
    }

    private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchButtonActionPerformed
        if (worker != null)
            worker.interrupt();

        worker = new Thread() {
            @Override
            public void run() {
                try
                {
                    SwingUtilities.invokeLater(new Runnable() {
                            public void run() {
                                jProgressBar1.setIndeterminate(true);
                            }
                        });
                    
                    listDocenti = webUnina.lookupDocente(docenteField.getText());
                    final DefaultTableModel t = getEmptyTableModel();

                    for (Docente d : listDocenti)
                    {
                        t.addRow(new Object[] { d.getCognomeDocente(), d.getNomeDocente(), d.getDipartimentoDocente() });
                    }
                    if (!isInterrupted())
                    {
                        SwingUtilities.invokeLater(new Runnable() {
                            public void run() {
                                docentiList.setModel(t);
                            }
                        });
                    }
                }
                catch (IOException e)
                {
                    exceptionThrown(e);
                }
                finally
                {
                    if (!isInterrupted())
                        SwingUtilities.invokeLater(new Runnable() {
                            public void run() {
                                jProgressBar1.setIndeterminate(false);
                            }
                        });
                }
            }
        };
        worker.start();
    }//GEN-LAST:event_searchButtonActionPerformed

    private DefaultTableModel getEmptyTableModel()
    {
        return new javax.swing.table.DefaultTableModel(
                new Object [][] {},
                new String [] {
                    "Cognome", "Nome", "Dipartimento"
                })
        {
            @Override
            public Class getColumnClass(int columnIndex) {
                return java.lang.String.class;
            }

            @Override
            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return false;
            }
        };
    }

    private void exceptionThrown(IOException e)
    {
        JOptionPane.showMessageDialog(this, "Errore nell'eseguire il comando:\n" + e.getMessage());
        dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
    }

    private void docenteFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_docenteFieldActionPerformed
        this.searchButton.doClick();
    }//GEN-LAST:event_docenteFieldActionPerformed

    private void docentiListKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_docentiListKeyReleased
        if (evt.isActionKey())
            frwdButton.doClick();
    }//GEN-LAST:event_docentiListKeyReleased

    private void docentiListMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_docentiListMouseClicked
        if (evt.getClickCount() == 2)
            frwdButton.doClick();
    }//GEN-LAST:event_docentiListMouseClicked

    private void insegnamentoListMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_insegnamentoListMouseClicked
        if (evt.getClickCount() == 2)
            frwdButton.doClick();
    }//GEN-LAST:event_insegnamentoListMouseClicked

    private void insegnamentoListKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_insegnamentoListKeyReleased
         if (evt.isActionKey())
            frwdButton.doClick();
    }//GEN-LAST:event_insegnamentoListKeyReleased

    public static Docente getDocente(final Frame parent, final WebDocentiUnina w)
    {
        Docente d = null;
        final UninaSelecter s = new UninaSelecter(parent, true, w, Selection.DOCENTE);
        final Runnable r = new Runnable() {
            public void run() {
                s.setLocationRelativeTo(null);
                s.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
                s.setVisible(true);
            }
        };

        try
        {
            if (SwingUtilities.isEventDispatchThread())
                r.run();
            else
                SwingUtilities.invokeAndWait(r);

            d = s.docSelected;
        }
        catch (InterruptedException e)
        {}
        catch (InvocationTargetException e)
        {}
        finally
        {
            s.dispose();
        }
        return d;
    }

    public static Insegnamento getInsegnamento(final Frame parent, final WebDocentiUnina w)
    {
        Insegnamento ins = null;
        final UninaSelecter s = new UninaSelecter(parent, true, w, Selection.DocANDInsSTEP1);
        final Runnable r = new Runnable() {
            public void run() {
                s.setLocationRelativeTo(null);
                s.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
                s.setVisible(true);
            }
        };

        try
        {
            if (SwingUtilities.isEventDispatchThread())
                r.run();
            else
                SwingUtilities.invokeAndWait(r);

            ins = s.insSelected;
        }
        catch (InterruptedException e)
        {}
        catch (InvocationTargetException e)
        {}
        finally
        {
            s.dispose();
        }
        return ins;
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton backButton;
    private javax.swing.JTextField docenteField;
    private javax.swing.JPanel docentePanel;
    private javax.swing.JTable docentiList;
    private javax.swing.JButton frwdButton;
    private javax.swing.JList insegnamentoList;
    private javax.swing.JPanel insegnamentoPanel;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private final javax.swing.JProgressBar jProgressBar1 = new javax.swing.JProgressBar();
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JButton searchButton;
    // End of variables declaration//GEN-END:variables
    private WebDocentiUnina webUnina;
    private Selection mode;
    private List<Docente> listDocenti;
    private List<Insegnamento> listInsegnamenti;
    protected Docente docSelected = null;
    protected Insegnamento insSelected = null;
    private Thread worker = null;

}
